package models

import (
	"go-web/utils"
	"strings"
)

type AdminMenu struct {
	utils.BaseModel
	Title    string      `json:"title" gorm:"size:50;comment:菜单标题"`
	ParentId uint        `json:"parent_id" gorm:"default:0;comment:父菜单id"`
	Link     string      `json:"link" gorm:"comment:链接"`
	Order    float32     `json:"order" gorm:"type:float(6,3);comment:排序，值越小越上面;index:idx_order"`
	Child    []AdminMenu `json:"child" gorm:"-"`
}

// GetMenuByUid 获取跟我有关的所有菜单，最多支持2级
func GetMenuByUid(uid uint) []AdminMenu {
	var all []AdminMenu
	user := GetUserByUid(uid)
	if user.ID <= 0 {
		return all
	}
	db := utils.GetDB()
	if strings.ToLower(user.Auth) == "all" {
		db.Order("`order` asc").Find(&all)
	} else if strings.ToLower(user.Auth) == "" {
		return all
	} else {
		db.Where("id in (?)", strings.Split(user.Auth, ",")).Order("`order` asc").Find(&all)
	}

	if len(all) <= 0 {
		return all
	}
	var parent []AdminMenu
	var child []AdminMenu
	for _, v := range all {
		if v.ParentId == 0 {
			parent = append(parent, v)
		} else {
			child = append(child, v)
		}
	}

	for k, v := range parent {
		for _, v2 := range child {
			if v2.ParentId == v.ID {
				parent[k].Child = append(parent[k].Child, v2)
			}
		}
	}
	return parent
}
